define(['jquery', 'bootstrap', 'backend', 'table', 'form','vue','layui','template','fileinput'], function ($, undefined, Backend, Table, Form,Vue,undefined,Template,fileinput) {
    var LayuiDir = requirejs.s.contexts._.config.baseUrl;//该路径为我实例项目路径，具体可以根据layui目录自行配置
    var layer;
    layui.config({dir: LayuiDir+'../libs/layui/'});//配置layui 所在目录
    layui.use(['form','upload'],function(){
        layer = layui.layer;
    });
    var option_item_component = Vue.component('option_item_component',{
        props: ['index','content','correct'],

        template:'#option_item',
        data: function () {
            return {
                myContent: this.content,
                myCorrect : this.correct
            };
        },
        watch: {
            content:function(val) {
                this.myContent = val;//②监听外部对props属性result的变更，并同步到组件内的data属性myResult中
            },
            myContent:function(val){
                this.$emit("on-content-change",val,this.index);//③组件内对myResult变更后向外部发送事件通知
            },
            correct:function(val) {
                console.info(val);
                this.myCorrect = val;//②监听外部对props属性result的变更，并同步到组件内的data属性myResult中
            },
            myCorrect:function(val){
                this.$emit("on-correct-change",val,this.index);//③组件内对myResult变更后向外部发送事件通知
            }
        },
        methods:{
            delOptionItemByComponent : function(index){
                console.info('del:'+index);
                delOptionItem(index);
            }
        }
    });
    function initFileInput(uploadUrl) {
        console.info(uploadUrl);
        $('#upload_file').fileinput('refresh',{
            language: 'zh', //设置语言
            uploadUrl: uploadUrl, //上传的地址
            allowedFileExtensions : ['xls','xlsx'],//接收的文件后缀
            showUpload: true, //是否显示上传按钮
            showRemove:false,
            showCaption: false,//是否显示标题
            browseClass: "btn btn-primary", //按钮样式
            initialPreviewConfig:[],
            allowedPreviewTypes: ['image'],
            previewFileIcon: "<i  class='glyphicon glyphicon-king'></i>",
        }).on("fileuploaded", function(event, data) {
            if(data.response.code == 1){
                Toastr.success(data.response.msg);
            }else{
                Toastr.error(data.response.msg);
            }
        }).on("filesuccessremove", function (event, data, previewId, index) {
            return false;
        });
    }
    var vue = new Vue({
        el:'#form_div',
        data:{
            is_choice : true,
            radio_items: [],
            category_list: [],
            sub_category_list: [],
            component_id : 0,
            category_id : 0,
            topic:{
                title:'',
                answer:'',
                grade:0,
                category_id:0,
                sub_category_id:0,
                is_use : 0,
            }
        },
        watch:{
            category_id:function (val) {
                this.category_id = val;
                this.topic.category_id = val;
                this.initSubCategoryList();
            }
        },
        methods: {
            addForm: function () {
                this.save('topic/add');
            },
            editForm:function(){
                this.save('topic/edit');
            },
            save:function(url){
                this.topic.title = $('#title').val();
                var postData = {
                    topic:this.topic,
                    radio_items:this.radio_items
                };
                var data = {data:postData};
                // console.info(postData);
                $.post(url, data, function (res) {
                    data = res;
                    console.info(data);
                    if(data.code == 1){
                        layer.msg(data.msg,{type:1},function () {
                            var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
                            parent.layer.close(index);
                            window.parent.location.reload();
                        });

                    }else{
                        Toastr.error(data.msg);
                    }
                }, 'json');
            },
            addOptionItem: function (component) {   //添加选项
                var item = {
                    'component': component,
                    'index' : this.component_id,
                    'content' : '',
                    'correct' : '0'
                };
                item.component = 'option_item_component';
                this.radio_items.push(item);
                this.component_id++;
            },
            onContentChange : function(val,index){
                var array;
                array = vue.radio_items;
                for(var i=0;i<array.length;i++){
                    var item = array[i];
                    if(item.index == index){
                        item.content = val;
                    }
                }
                // array[index].content = val;
            },
            onCorrectChange : function(val,index){
                console.info(val+'---'+index);
                var array;
                array = vue.radio_items;
                for (var i = 0; i < array.length; i++) {
                    var item = array[i];
                    item.correct = '0';
                }
                for (var i = 0; i < array.length; i++) {
                    var item = array[i];
                    if(item.index == index){
                        item.correct = val;
                    }
                }
            },
            initSubCategoryList:function () {
                var data = {'parent_id':this.category_id};
                var that = this;
                $.get('admin_public/ajax_category_list', data, function (res) {
                    that.sub_category_list = res;
                });
            },
            initCategoryList:function () {
                var data = {'parent_id':0};
                var that = this;
                $.get('admin_public/ajax_category_list', data, function (res) {
                    that.category_list = res;
                });
            }
        },
        components: {
            'option_item_component': option_item_component
        }
    });
    function delOptionItem(id){
        var array;
        array = vue.radio_items;
        for(var i=0;i<array.length;i++){
            var item = array[i];
            if(item.index == id){
                array.splice(i,1);
            }
        }
    }

    Array.prototype.unique = function(){
        this.sort(); //先排序
        var res = [this[0]];
        for(var i = 1; i < this.length; i++){
            if(this[i] !== res[res.length - 1]){
                res.push(this[i]);
            }
        }
        return res;
    };
    function getArray(a) {
        var hash = {},
            len = a.length,
            result = [];

        for (var i = 0; i < len; i++){
            if (!hash[a[i]]){
                hash[a[i]] = true;
                result.push(a[i]);
            }
        }
        return result;
    }
    function removeByValue(arr, val) {
        for(var i=0; i<arr.length; i++) {
            if(arr[i] == val) {
                arr.splice(i, 1);
                break;
            }
        }
    }
    function init() {
        vue.initCategoryList();

        var topic_id = $('#topic_id').val();
        if(typeof(topic_id)!='undefined' && topic_id !=''){
            var data = {'id':topic_id};
            $.get('topic/getTopic', data, function (res) {

                vue.topic = res;
                var items = res.option_items;
                for (var i = 0; i < items.length; i++) {
                    var item = items[i];
                    item.index = i;
                    item.component = 'option_item_component';
                    item.correct = item.is_correct;
                    item.component_id = i;
                }
                vue.component_id = items.length;
                vue.radio_items = items;
                vue.category_id = vue.topic.category_id;
                vue.initSubCategoryList();
                delete vue.topic.option_items;
            }, 'json');
        }
    }
    function initSearchVue() {
        var category_vue = new Vue({
            el:"#category_div",
            data:{
                category_list: []
            },
            watch: {
            },
            methods:{
                initCategoryList:function () {
                    var that = this;
                    var data = {
                        parent_id : 0
                    };
                    $.post("admin_public/ajax_category_list",data,function(result) {
                        that.category_list = result;
                    });
                }
            }
        });
        var sub_category_vue = new Vue({
            el:"#sub_category_div",
            data:{
                sub_category_list: [],
                parent_id:0,
            },
            watch: {
                parent_id:function (val) {
                    this.parent_id = val;
                    this.initCategoryList();
                }
            },
            methods:{
                initCategoryList:function () {
                    var that = this;
                    var data = {
                        parent_id : this.parent_id
                    };
                    $.post("admin_public/ajax_category_list",data,function(result) {
                        that.sub_category_list = result;
                    });
                }
            }
        });
        $('select[name=category_id]').on('change', function () {
            sub_category_vue.parent_id = this.value;
        });
        category_vue.initCategoryList();
    }
    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'topic/index',
                    add_url: 'topic/add',
                    edit_url: 'topic/edit'
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                search:false,
                columns: [
                    [
                        {field: 'state', checkbox: true },
                        {field: 'id', title: 'ID'},
                        {field: 'title', title: __('Title'),operate: 'LIKE %...%', placeholder: '模糊搜索'},
                        {field: 'category_name', title: __('Category'),searchable:false},
                        {field: 'sub_category_name', title: __('Sub category'),searchable:false},
                        {field: 'is_use', title: __('Is use'), sortable:true,
                            searchList: {"0": __('Do not use'), "1": __('Use')},
                            formatter:function(value,row,index){
                                value = value + '';
                                switch (value){
                                    case '0':
                                        return __('Do not use');
                                    case '1':
                                        return __('Use');
                                    default:
                                        return __('Do not use');
                                }
                            } },
                        {field: 'grade', title: __('Grade'), sortable:true,
                            searchList: {"0": __('Grade 1'), "1": __('Grade 2'),'2':__('Grade 3'),'3':__('Grade 4'),'4':__('Grade 5')},
                            formatter:function(value,row,index){
                                value = value + '';
                                switch (value){
                                    case '0':
                                        return __('Grade 1');
                                    case '1':
                                        return __('Grade 2');
                                    case '2':
                                        return __('Grade 3');
                                    case '3':
                                        return __('Grade 4');
                                    case '4':
                                        return __('Grade 5');
                                    default:
                                        return __('Grade 5');
                                }
                            } },
                        {field: 'category_id', title: __('Category'),visible:false,searchList: function (column) {
                            return Template('category_search', {});}
                        },
                        {field: 'sub_category_id', title: __('Sub category'),visible:false,searchList: function (column) {
                            return Template('sub_category_search', {});}
                        },
                        {field: 'operate', title: __('Operate'), table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });
            initSearchVue();
            // 为表格绑定事件
            Table.api.bindevent(table);
            $(document).on("click", ".btn-shelves", function () {
                var selections = table.bootstrapTable('getSelections');
                var ids = [];
                $(selections).each(function(i,item){
                    ids.push(item.id);
                });
                console.info(ids);
                $.ajax({
                    url:Config.site.cdnurl+'/index.php/admin/topic/shelves',
                    type:'POST', //GET
                    data:{
                        topic_ids:ids
                    },
                    timeout:5000,    //超时时间
                    dataType:'json',    //返回的数据格式：json/xml/html/script/jsonp/text
                    success:function(data){
                        if(data.code == 1){
                            Toastr.success(data.msg);
                            $("#table").bootstrapTable('refresh');
                        }else{
                            Toastr.error(data.msg);
                        }
                    },
                    error:function(xhr,textStatus){
                        Toastr.error('服务器繁忙，请稍后再试！');
                    }
                })
            });
            $(document).on("click", ".btn-the-shelves", function () {
                var selections = table.bootstrapTable('getSelections');
                var ids = [];
                $(selections).each(function(i,item){
                    ids.push(item.id);
                });
                console.info(ids);
                $.ajax({
                    url:Config.site.cdnurl+'/index.php/admin/topic/the_shelves',
                    type:'POST', //GET
                    data:{
                        topic_ids:ids
                    },
                    timeout:5000,    //超时时间
                    dataType:'json',    //返回的数据格式：json/xml/html/script/jsonp/text
                    success:function(data,textStatus,jqXHR){
                        if(data.code == 1){
                            Toastr.success(data.msg);
                            $("#table").bootstrapTable('refresh');
                        }else{
                            Toastr.error(data.msg);
                        }
                    },
                    error:function(xhr,textStatus){
                        Toastr.error('服务器繁忙，请稍后再试！');
                    }
                })
            });
            var url = Config.site.cdnurl+'/index.php/admin/topic/import';
            // initFileInput(url);
            $(document).on("click", ".btn-import", function () {
                $('#uploadModal').modal();

            });
            $(document).on("click", "#upload_btn", function () {
                var form = new FormData(document.getElementById("upload_form"));
                console.info(form);
                $.ajax({
                    url: Config.site.cdnurl+'/index.php/admin/topic/import',
                    type: "POST",
                    data: form,
                    processData: false,
                    contentType: false,
                    success: function (data) {
                        if(data.code == 1){
                            Toastr.success(data.msg);
                            $('#uploadModal').modal('hide');
                        }else{
                            Toastr.error(data.msg);
                        }
                    },
                    error: function (e) {
                    }
                });
            });
        },
        add: function () {
            Form.api.bindevent($("form[role=form]"));
            init();
            $('#add_button').unbind('click');
            $('#add_button').on('click',function () {
                vue.addForm();
            });
        },
        edit: function () {
            Form.api.bindevent($("form[role=form]"));
            init();
            $('#edit_button').unbind('click');
            $('#edit_button').on('click',function () {
                vue.editForm();
            });

        },
        detail:function(){
            Form.api.bindevent($("form[role=form]"));
        }
    };
    return Controller;
});